home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 10 / AACD 10.iso / AACD / Online / SpeakFreely / src / deskey.c < prev    next >
C/C++ Source or Header  |  2000-05-18  |  2KB  |  80 lines

  1. /*
  2. * Convert character string to 56-bit DES key, contained in 8 bytes
  3. * (including parity):
  4. * - Strip leading and trailing white space; compress multiple spaces
  5. * - compute MD5 hash
  6. * - extract 7 bit pieces into bytes
  7. * - compute parity
  8. *
  9. * The algorithm specifier must be 16 bytes long.
  10. */
  11.  
  12. #include "speakfree.h"
  13.  
  14. #ifdef CRYPTO
  15.  
  16. #define MAX_KEY 256
  17.  
  18. #define MD_CTX MD5_CTX
  19. #define MDInit MD5Init
  20. #define MDUpdate MD5Update
  21. #define MDFinal MD5Final
  22.  
  23. void string_DES_key(key, des_key, algorithm)
  24.   char *key;
  25.   unsigned char des_key[8];
  26.   char algorithm[16];
  27. {
  28.   char *s, *d;
  29.   char c[MAX_KEY+1];
  30.   int seen_white = 0;
  31.   unsigned char digest[16];
  32.   MD_CTX context;
  33.  
  34.   /* white space trimming, conversion and compression */
  35.   for (s = key, d = c; *s && (d - c < MAX_KEY); s++) {
  36.     if (isspace(*s)) {
  37.       seen_white = 1;
  38.     }
  39.     else {
  40.       if (seen_white) {
  41.     seen_white = 0;
  42.         if (d != c) *d++ = ' ';
  43.       }
  44.       *d++ = tolower(*s);
  45.     }
  46.   }
  47.   *d = '\0';
  48.  
  49.   /* extract algorithm specifier, if any */
  50.   strcpy(algorithm, "DES-CBC");
  51.   if ((s = strchr(c, '/')) && s - key < 16) {
  52.     *s = '\0';
  53.     s++; /* skip slash */
  54.     for (d = c; *d; d++) {
  55.       *d = toupper(*d);
  56.     }
  57.     strcpy(algorithm, c);
  58.   }
  59.   else s = c;
  60.  
  61.   /* compute MD5 hash */
  62.   MDInit(&context);
  63.   MDUpdate(&context, (unsigned char *)s, strlen(s));
  64.   MDFinal(digest, &context);
  65.  
  66.   /* extract 8 7-bit bytes */
  67.   des_key[0] = (digest[0] & 0xfe) >> 1;
  68.   des_key[1] = ((digest[0] & 0x01) << 6) | ((digest[1] & 0xfc) >> 2);
  69.   des_key[2] = ((digest[1] & 0x03) << 5) | ((digest[2] & 0xf8) >> 3);
  70.   des_key[3] = ((digest[2] & 0x07) << 4) | ((digest[3] & 0xf0) >> 4);
  71.   des_key[4] = ((digest[3] & 0x0f) << 3) | ((digest[4] & 0xe0) >> 5);
  72.   des_key[5] = ((digest[4] & 0x1f) << 2) | ((digest[5] & 0xc0) >> 6);
  73.   des_key[6] = ((digest[5] & 0x3f) << 1) | ((digest[6] & 0x80) >> 7);
  74.   des_key[7] = digest[6] & 0x0f;
  75.  
  76.   /* compute parity */
  77.   des_set_odd_parity((des_cblock *)des_key);
  78. }
  79. #endif
  80.